#ifndef PMT_H
#define PMT_H

#ifdef __cplusplus
extern "C"
{
#endif

/*****************************************************************************
 * Program Map Table
 *****************************************************************************/
#define PMT_TABLE_ID            SI_TID_PMT
#define PMT_HEADER_SIZE         (SI_HEADER_SIZE_SYNTAX1 + 4)
#define PMT_ES_SIZE             5

static inline ms_s32 pmt_api_build( ms_byte *ptspkt,ms_u08 *cc,ms_u08 pktSize,ms_byte adaption_field_control,
	ms_u16 program_num,ms_u16 pid,ms_u16 pcr_pid,ms_s08 num_es, ESInfo *pEsInfoArry)
{
//构建PMT的TS头 
	mssi_api_tsInit(ptspkt,pid,(*cc), pktSize,adaption_field_control,0x01);
	(*cc)+=1;
//查找PMT数据位置
	ms_s32 es_index=0;
	ms_u08 totalLen_esInfo=0;
	for(es_index=0;es_index<num_es;es_index++){
		ESInfo *pEsInfo=&pEsInfoArry[es_index];
		totalLen_esInfo+=(PMT_ES_SIZE+pEsInfo->len_esInfo);
	}
	ms_u16 section_len=(1+PMT_HEADER_SIZE)+totalLen_esInfo;
	ms_byte *ptspkt_pmt=mssi_api_setAdaptationFieldLen(adaption_field_control, section_len, ptspkt,0);
	if(ms_null==ptspkt_pmt){
		return 0;
	}
	
//第一字节填0：1字节		
	ptspkt_pmt[0]=0x00;
	ms_byte *p_pmt=&ptspkt_pmt[1];

//构建SYNTAX1头部：8字节					
	mssi_api_buildSyntax1Head(p_pmt, SI_TID_PMT, section_len, program_num,0,0,0);
	
//构建SYNTAX2头部：4字节	
	ms_byte *p_pmt2=&p_pmt[SI_HEADER_SIZE_SYNTAX1];
/*	[15:13]res
	[12:00]pcr_pid：私有数据设置为0x1FFF*/
	p_pmt2[0]=(0x07<<5)&0xE0;
	p_pmt2[0]|=(pcr_pid>>8)&0x1F;
	p_pmt2[1]=pcr_pid&0xFF;
/*	[15:12]res
	[11:00]pgrpgram_info_len：前2位为00*/	
	p_pmt2[2]=(0x0F<<4)&0xF0;
	ms_u08 pgrpgram_info_len=0x00;
	p_pmt2[2]|=(pgrpgram_info_len>>8)&0x0F;
	p_pmt2[3]=pgrpgram_info_len&0xFF;
	
//构建ES信息：num_es*(5+len_esInfo)
	ms_byte *p_pmte=&p_pmt2[4];
	ms_s32 es_offset=0;
	for(es_index=0;es_index<num_es;es_index++){
		ESInfo *pEsInfo=&pEsInfoArry[es_index];
	/*	[07:00]streamType*/	
		p_pmte[es_offset++]=pEsInfo->streamType&0xFF;
	/*	[15:13]res
		[12:00]pid：前2位为00*/
		p_pmte[es_offset]=(0x07<<5)&0xE0;
		p_pmte[es_offset++]|=(pEsInfo->pid>>8)&0x1F;
		p_pmte[es_offset++]=pEsInfo->pid&0xFF;
	/*	[15:12]res
		[11:00]es_info_len：前2位为00*/
		p_pmte[es_offset]=(0x0F<<4)&0xF0;
		p_pmte[es_offset++]|=(pEsInfo->len_esInfo>>8)&0x0F;
		p_pmte[es_offset++]=pEsInfo->len_esInfo&0xFF;
		if(pEsInfo->len_esInfo>0){
			ms_memcpy(&p_pmte[es_offset], pEsInfo->esInfo, pEsInfo->len_esInfo);
			es_offset+=pEsInfo->len_esInfo;
		}
	}
	
//构建CRC：4字节	
	ms_u32 crc=mscrc_api_CRC32(p_pmt, (section_len-1));
	ms_network_4b((&p_pmte[es_offset]), crc);
	
	return pktSize;
}
	

#ifdef __cplusplus
}
#endif

#endif
